<template>
  <div class="applyForm">
    <div class="logo">
      <img src="@/assets/images/logoTop.png" alt/>
    </div>
    <h2 class="title">报名信息</h2>
    <i-form ref="formbox" :model="formInline" :rules="ruleInline" inline>
      <div class="formBox">
        <div class="form_item">
          <div class="name">姓名</div>
          <div class="box">
            <Form-item prop="name">
              <i-input
                type="text"
                class="form_control"
                v-model="formInline.name"
                placeholder="与身份证信息一致"
              ></i-input>
            </Form-item>
          </div>
        </div>
        <div class="form_item">
          <div class="name">电话</div>
          <div class="box">
            <Form-item prop="phone">
              <i-input
                type="text"
                class="form_control"
                v-model="formInline.phone"
                placeholder="填写手机号"
              ></i-input>
            </Form-item>
          </div>
        </div>
        <div class="form_item">
          <div class="name">身份证号</div>
          <div class="box">
            <Form-item prop="idcard">
              <i-input
                type="text"
                class="form_control"
                placeholder="与身份证信息一致"
                v-model="formInline.idcard"
              ></i-input>
            </Form-item>
          </div>
        </div>
        <div class="form_item address">
          <div class="name">家庭地址</div>
          <div class="box">
            <Form-item prop="home_province" class="wd122">
              <i-input
                type="text"
                class="form_control"
                disabled
                value="四川"
                v-model="formInline.home_province"
              ></i-input>
            </Form-item>
            省
            <Form-item prop="home_city" class="wd122">
              <i-input type="text" class="form_control" v-model="formInline.home_city"></i-input>
            </Form-item>
            市
            <div class="address_box">
              <Form-item prop="home_address">
                <i-input
                  type="text"
                  class="form_control"
                  v-model="formInline.home_address"
                  placeholder="请正确填写详细家庭住址"
                ></i-input>
              </Form-item>
            </div>
          </div>
        </div>
        <div class="form_item">
          <div class="name">职业</div>
          <div class="box">
            <Form-item prop="job">
              <i-input type="text" class="form_control" v-model="formInline.job"></i-input>
            </Form-item>
          </div>
        </div>
        <div class="form_item">
          <div class="name">工作单位</div>
          <div class="box">
            <Form-item prop="workunit">
              <i-input type="text" class="form_control" v-model="formInline.workunit"></i-input>
            </Form-item>
          </div>
        </div>
        <div class="form_item">
          <div class="name">出发城市</div>
          <div class="box">
            <Form-item prop="start_city">
              <i-select
                v-model="formInline.start_city"
                placeholder="请选择"
                @on-change="startCityChange"
              >
                <i-option :value="v" v-for="(v,i) in departureData" :key="i">{{v}}</i-option>
              </i-select>
            </Form-item>
          </div>
        </div>
        <div class="form_item">
          <div class="name">到达城市</div>
          <div class="box">
            <Form-item prop="end_city">
              <i-select v-model="formInline.end_city" placeholder="请选择">
                <i-option :value="v" v-for="(v,i) in destinateData" :key="i">{{v}}</i-option>
              </i-select>
            </Form-item>
          </div>
        </div>
        <div class="form_item uploadCard">
          <div class="name">
            身份证
            <p>二代身份证</p>
          </div>
          <div class="box">
            <div class="idCardUpladBtn" @click="uploadHeadImg(1)" v-if="!formInline.card_front">
              <div class="p1">点击上传</div>
              <div class="p2">正面</div>
            </div>
            <div
              class="idCardUpladBtn"
              :class="{set:formInline.card_front}"
              @click="uploadHeadImg(1)"
              v-if="formInline.card_front"
            >
              <img :src="(imgUrl+formInline.card_front)" alt/>
            </div>
            <div class="idCardUpladBtn" @click="uploadHeadImg(0)" v-if="!formInline.card_back">
              <div class="p1">点击上传</div>
              <div class="p2">反面</div>
            </div>
            <div
              class="idCardUpladBtn"
              :class="{set:formInline.card_back}"
              @click="uploadHeadImg(0)"
              v-if="formInline.card_back"
            >
              <img :src="(imgUrl+formInline.card_back)" alt/>
            </div>
          </div>
        </div>
      </div>
    </i-form>
    <div class="applyAgreement">
      <input type="checkbox" class="fish_radio" v-model="hasAgree"/>
      <span @click="viewAgreement">同意该《隐私保密协议》</span>
    </div>
    <div class="btn">
      <a href="javascript:void(0);" class="applyBtn" @click="submitForm">提 交</a>
    </div>
  </div>
</template>
<script>
  var wx = require("weixin-js-sdk");
  import {mapActions} from "vuex";
  import axios from "axios";

  export default {
    data() {
      return {
        imgUrl: "http://zhiyang.yizehd.com",
        formInline: {
          name: "",
          phone: "",
          idcard: "",
          home_province: "四川",
          home_city: "",
          home_address: "",
          job: "",
          workunit: "",
          start_city: "",
          end_city: "",
          card_front: "",
          card_back: ""
        },
        ruleInline: {
          name: [{required: true, message: "", trigger: "blur"}],
          phone: [
            {required: true, message: "", trigger: "blur"},
            {
              pattern: /^1[3456789]\d{9}$/,
              message: "",
              trigger: "blur"
            }
          ],
          idcard: [
            {required: true, message: "", trigger: "blur"},
            {
              pattern: /^[1-9]\d{5}(18|19|20|(3\d))\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/,
              message: "",
              trigger: "blur"
            }
          ],
          home_province: [{required: true, message: "", trigger: "blur"}],
          home_city: [{required: true, message: "", trigger: "blur"}],
          home_address: [{required: true, message: "", trigger: "blur"}],
          job: [{required: true, message: "", trigger: "blur"}],
          workunit: [{required: true, message: "", trigger: "blur"}],
          start_city: [{required: true, message: "", trigger: "change"}],
          end_city: [{required: true, message: "", trigger: "change"}]
        },
        departureData: [
          "北京",
          "上海",
          "苏州",
          "无锡",
          "福州",
          "南昌",
          "常州",
          "南京"
        ],
        destinateData: [],
        card_front: "",
        card_back: "",
        hasAgree: false,
        carReg: /^[1-9]\d{5}(18|19|20|(3\d))\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/,
        carInfo: null
      };
    },
    mounted() {
      this.$nextTick(() => {
        this.getShareInfo({
          url: location.href.split("#")[0],
          callback: res => {
            wx.ready(() => {
              wx.config({
                debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                appId: res.data.appId, // 必填，公众号的唯一标识
                timestamp: res.data.timestamp, // 必填，生成签名的时间戳
                nonceStr: res.data.nonceStr, // 必填，生成签名的随机串
                signature: res.data.signature, // 必填，签名
                jsApiList: ["chooseImage", "uploadImage"]
              });
            });
          }
        });

        let tickeInfo = localStorage.getItem("applyData")
        let applyDatacarInfo = localStorage.getItem("applyDatacarInfo")

        if (applyDatacarInfo) {
          this.carInfo = JSON.parse(applyDatacarInfo)
          localStorage.removeItem("applyDatacarInfo");
        }
        if (tickeInfo) {
          tickeInfo = JSON.parse(tickeInfo)
          this.formInline = tickeInfo;
          this.card_front = tickeInfo.card_front;
          this.card_back = tickeInfo.card_back;
          this.carInfo = tickeInfo;
          this.carInfo.code = tickeInfo.idcard;
          this.hasAgree = true;
          this.setaddressVal(tickeInfo.start_city);
          localStorage.removeItem("applyData");
        }
        const val = window.sessionStorage.getItem("yizehdty");
        if (val && Number(val) === 1) {
          this.hasAgree = true;
        } else {
          this.hasAgree = false;
        }
      });
    },
    methods: {
      ...mapActions({
        getShareInfo: "fishH5/getShareInfo",
        // saveTicketInfo: "fishH5/saveTicketInfo",
        getTicketInfo: "fishH5/getTicketInfo"
      }),

      startCityChange(val) {
        this.setaddressVal(val);
      },
      setaddressVal(val) {
        this.destinateData = [];
        if (val == "北京") {
          this.destinateData = ["广元", "青川", "江油", "绵阳", "德阳", "成都"];
        } else if (
          val == "上海" ||
          val == "苏州" ||
          val == "无锡" ||
          val == "常州" ||
          val == "南京"
        ) {
          this.destinateData = ["广元", "江油", "绵阳", "德阳", "成都"];
        } else if (val == "福州" || val == "南昌") {
          this.destinateData = ["成都"];
        }
      },
      uploadHeadImg(type) {
        let that = this;
        if (!this.formInline.name) {
          that.$Message.error("请输入姓名");
          return;
        }
        if (!this.carReg.test(this.formInline.idcard)) {
          that.$Message.error("请输入正确的身份证号码");
          return;
        }
        wx.ready(() => {
          wx.chooseImage({
            count: 1, // 默认9
            sizeType: ["compressed"], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: ["album", "camera"], // 可以指定来源是相册还是相机，默认二者都有
            success: function (res) {
              that.uploadImage(res.localIds[0], type);
              //that.getLocalImgData(res.localIds[0], type)
            }
          });
        });
      },
      uploadImage(localId, type) {
        const that = this;
        wx.uploadImage({
          localId: localId,
          isShowProgressTips: 1, // 默认为1，显示进度提示
          success: async res => {
            const serverId = res.serverId; // 返回图片的服务器端ID
            let mytype = "back";
            if (type) {
              mytype = "front";
            }
            const result = await that.upLoadCard(serverId, mytype);
            if (type) {
              if (result && result.data.code > 0) {
                const data = result.data.data;
                if (data.name && that.carReg.test(data.code)) {
                  that.carInfo = data;
                  that.formInline.idcard = that.carInfo.code;
                  that.formInline.name = that.carInfo.name;
                  that.formInline.card_front = that.carInfo.imgurl;
                } else {
                  that.$Message.error("未能正确识别身份证正面，请重新上传");
                }
              } else {
                that.$Message.error("未能正确识别身份证正面，请重新上传");
              }
            } else {
              if (result && result.data.code > 0) {
                const data = result.data.data;
                that.formInline.card_back = data.imgurl;
              } else {
                that.$Message.error("未能正确识别身份证反面，请重新上传");
              }
            }
          }
        });
      },
      getLocalImgData(localId, type) {
        let that = this;
        wx.getLocalImgData({
          localId,
          success: async res => {
            const result = await that.upLoadCard(res.localData);
            if (type) {
              if (result && result.data.code > 0) {
                const data = result.data.data;
                if (
                  data.code === that.formInline.idcard &&
                  data.name === that.formInline.name
                ) {
                  that.formInline.card_front = data.imgurl;
                } else {
                  that.$Message.error("身份证号和姓名不匹配");
                }
              } else {
                that.$Message.error("未能正确识别身份证正面，请重新上传");
              }
            } else {
              if (result && result.data.code > 0) {
                const data = result.data.data;
                that.formInline.card_back = data.imgurl;
              } else {
                that.$Message.error("未能正确识别身份证反面，请重新上传");
              }
            }
          }
        });
      },
      upLoadCard(media_id, type = "front") {
        return axios.post("api/ticket/checkCardOcr", {media_id, type});
      },
      viewAgreement() {
        if ((this.hasAgree = true)) {
          window.sessionStorage.setItem("yizehdty", 1);
        }
        localStorage.setItem("applyData", JSON.stringify(this.formInline));
        localStorage.setItem("applyDatacarInfo", JSON.stringify(this.carInfo));
        this.$router.replace({
          path: "/ticketAgreement"
        });
      },
      submitForm() {
        if (!this.hasAgree) {
          this.$Message.error("您未同意同意该《隐私保密协议》，无法提交");
          return;
        }
        this.$refs["formbox"].validate(valid => {
          if (valid) {
            if (!this.formInline.card_back || !this.formInline.card_front) {
              this.$Message.error("未上传有效的身份证");
              return;
            }
            if (!this.hasAgree) {
              this.$Message.error("请勾选协议");
              return;
            }
            if (this.formInline.idcard !== this.carInfo.code) {
              this.$Message.error("所填身份证号码与上传的身份证身份证号码不匹配");
              return;
            }
            if (this.formInline.name !== this.carInfo.name) {
              this.$Message.error("所填姓名与上传的身份证姓名不匹配");
              return;
            }
            let data = this.formInline;

            localStorage.setItem("applyData", JSON.stringify(data));
            localStorage.setItem("applyDatacarInfo", JSON.stringify(this.carInfo));

            this.$router.replace({
              path: "/ticketConfirm"
            });
          } else {
          }
        });
      }
    }
  };
</script>
<style scoped>
  .applyForm {
    padding: 1.03rem 0.74rem 0 0.89rem;
    position: relative;
  }

  .applyForm .logo {
    width: 2.86rem;
    height: 0.86rem;
    position: absolute;
    top: 0.4rem;
    right: 0.46rem;
  }

  .applyForm .logo img {
    width: 100%;
    height: 100%;
  }

  .applyForm h2.title {
    font-size: 0.5rem;
    color: #e60012;
  }

  .applyForm .formBox .form_item {
    display: flex;
    width: 100%;
    padding: 0.13rem 0;
  }

  .form_item.address input.form-control {
    display: inline-block;
    vertical-align: middle;
  }

  .applyForm .formBox .name {
    width: 1.5rem;
    text-align: justify;
    text-align-last: justify;
    font-size: 0.33rem;
    line-height: 0.53rem;
    font-weight: bold;
    padding-right: 0.14rem;
  }

  .applyForm .formBox .box {
    flex: 1;
    font-size: 0.33rem;
    line-height: 0.53rem;
  }

  .address_box {
    padding-top: 0.23rem;
  }

  .uploadCard .name p {
    font-size: 0.19rem;
    line-height: 0.19rem;
    margin-top: 0.1rem;
  }

  .uploadCard .name {
    padding-top: 0.2rem;
  }

  .form-control {
    height: 0.53rem;
    display: block;
    border-radius: 0.1rem;
    -webkit-border-radius: 0.1rem;
    border: 1px solid #a0a0a0;
    width: 100%;
    padding: 0 10px;
    font-size: 0.22rem;
  }

  .idCardUpladBtn {
    display: inline-block;
    width: 2.06rem;
    height: 1.36rem;
    border: 1px solid #959595;
    border-radius: 0.1rem;
    background-color: #fef7f2;
    text-align: center;
    padding-top: 0.34rem;
    vertical-align: top;
  }

  .idCardUpladBtn img {
    width: 100%;
    height: 100%;
  }

  .idCardUpladBtn.set {
    padding-top: 0;
    overflow: hidden;
  }

  .idCardUpladBtn input {
    display: none;
  }

  .idCardUpladBtn .p1 {
    font-size: 0.18rem;
    color: #727171;
    line-height: 0.18rem;
  }

  .idCardUpladBtn .p2 {
    font-size: 0.32rem;
    color: #727171;
    line-height: 0.32rem;
    margin-top: 0.12rem;
  }

  .wd122 {
    width: 1.22rem;
  }

  .applyAgreement {
    text-align: center;
  }

  .applyAgreement input {
    vertical-align: middle;
  }

  .applyAgreement span {
    text-decoration: underline;
    font-size: 0.26rem;
    color: #0036ff;
    vertical-align: middle;
  }

  .applyForm .applyBtn {
    display: inline-block;
    width: 5.26rem;
    height: 0.96rem;
    background: url(~@/assets/images/assis_btn.png) no-repeat;
    background-size: 5.26rem 0.96rem;
    text-align: center;
    color: #fff;
    font-size: 0.48rem;
    line-height: 0.96rem;
    vertical-align: top;
  }

  .applyForm .btn {
    margin-bottom: 0.86rem;
    margin-top: 0.28rem;
    height: 0.96rem;
    text-align: center;
  }

</style>
